/**
 * Copyright (C) 2008 GeoScheduler Team, as stated on <http://www.geoscheduler.org/authors>.
 * 
 * This file is part of GeoScheduler.
 * 
 * GeoScheduler is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * GeoScheduler is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with GeoScheduler. If not, see <http://www.gnu.org/licenses/>.
 */

package org.geoscheduler.commons.marshaller.decls;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.geoscheduler.commons.marshaller.JSONFieldDecl;
import org.geoscheduler.commons.marshaller.JSONMarshaller;
import org.geoscheduler.commons.tools.PropertyDescriptor;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * 
 * <h2>JSONCollectionField</h2>
 * <p>
 * {@link Collection} property marshaller/unmarshaller
 * </p>
 * 
 * @author lko
 */
public class JSONCollectionField extends JSONAbstractFieldDecl<Collection<Object>> {

	public JSONCollectionField(PropertyDescriptor<Collection<Object>> desc, Collection<Object> defValue) {
		super(desc, defValue);
	}

	public JSONCollectionField(PropertyDescriptor<Collection<Object>> desc) {
		super(desc);
	}

	/**
	 * Marshall Collection as json encoded array
	 * 
	 * @see org.geoscheduler.commons.marshaller.JSONFieldDecl#marshall(org.geoscheduler.commons.marshaller.JSONMarshaller,
	 *      java.lang.Object, org.json.JSONObject)
	 */
	public JSONObject marshall(JSONMarshaller marshaller, Object instance, JSONObject obj) throws JSONException {
		PropertyDescriptor<Collection<Object>> desc = getDescriptor();

		Collection<Object> valueInst = desc.getValue(instance);
		if (valueInst == null) {
			obj.put(desc.getName(), JSONObject.NULL);
		} else {
			JSONArray array = new JSONArray();
			int index = 0;
			for (Object val : valueInst) {
				array.put(index, marshaller.marshall(val, new JSONObject()));
				index++;
			}
			obj.put(desc.getName(), array);
		}
		return obj;
	}

	/**
	 * Unmarshall JSON encoded array to Collection. Implementation tries to
	 * discover collection type from property type. If property type declares
	 * interface, than default implicit values are used:
	 * <ul>
	 * 	<li>List - {@link ArrayList}</li>
	 *  <li>Set  - {@link HashSet}</li>
	 * </ul> 
	 * 
	 * @see org.geoscheduler.commons.marshaller.JSONFieldDecl#unmarshall(org.geoscheduler.commons.marshaller.JSONMarshaller,
	 *      java.lang.Object, org.json.JSONObject)
	 */
	public Object unmarshall(JSONMarshaller marshaller, Object instance, JSONObject obj) throws JSONException {
		PropertyDescriptor<Collection<Object>> desc = getDescriptor();
		if (!obj.has(desc.getName())) {
			// we don't have to solve uninitialized collections
			return instance;
		}

		Collection<Object> col=null;
		try {
			Class<?> type = getType();
			if (type.isInterface()) {
				if (List.class.isAssignableFrom(type)) {
					col = new ArrayList<Object>();
				} else if (Set.class.isAssignableFrom(type)) {
					col = new HashSet<Object>();
				}
				throw new IllegalStateException("Unsupported collection extending interface " + type);
			} else {
				col = getType().newInstance();
			}

			JSONArray array = obj.getJSONArray(desc.getName());

			Class<?> elementClazz = getAnnotation().elementType();
			int len = array.length();
			for (int i = 0; i < len; i++) {
				col.add(marshaller.unmarshall(elementClazz.newInstance(), array.getJSONObject(i)));
			}
		} catch (InstantiationException ex) {
			throw new IllegalStateException("failed to instantiate collection", ex);
		} catch (IllegalAccessException ex) {
			throw new IllegalStateException("failed to access collection", ex);
		}
		//Other exceptions than declared will cause stack to go up
		return instance;

	}

	public static class Factory extends BaseAbstractFactory<Collection<Object>> {

		public JSONFieldDecl<Collection<Object>> create(PropertyDescriptor<Collection<Object>> desc,
				JSONMarshaller marshaller) {
			return new JSONCollectionField(desc);
		}

		public boolean isApplicable(PropertyDescriptor<?> desc) {
			return super.isApplicable(desc) && Collection.class.isAssignableFrom(desc.getType());
		}

	}
}
